<template>
  <div class="activity-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          新建
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="输入项目名称"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="number"
        label="项目编号"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="activity_name"
        label="项目名称"
      />
      <el-table-column align="center" show-overflow-tooltip label="项目时间">
        <template #default="{ row }">
          {{ row.activity_start }}~
          {{ row.activity_end }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240">
        <template #default="{ row }">
          <el-button
            type="text"
            :disabled="row.is_del === 2 || row.is_filed == '是'"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            :disabled="row.is_filed == '是'"
            type="text"
            @click="handleExpenses(row)"
          >
            结算信息
          </el-button>
          <el-button
            :disabled="row.is_filed == '是'"
            type="text"
            @click="showChecks(row.id)"
          >
            审批材料
          </el-button>
          <el-button
            type="text"
            :disabled="row.is_del === 2 || row.is_filed == '是'"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button type="text" @click="handleFiled(row)">
            {{ row.is_filed === '是' ? '解档' : '归档' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <edit ref="edit" @fetch-data="fetchData"/>

    <el-dialog
      v-if="checksVisible"
      title="审批材料"
      :visible.sync="checksVisible"
      width="800px"
      top="50px"
    >
      <el-upload
        v-if="!canUploadFile"
        action="#"
        :auto-upload="false"
        multiple
        :limit="6"
        :on-exceed="onChecksExceed"
        :on-change="(file, fileList) => onChecksChange(file)"
        :show-file-list="false"
      >
        <el-button type="primary">点击上传</el-button>
      </el-upload>
      <el-form v-if="!canUploadFile" label-position="top">
        <el-table :data="checkTypes.fileList">
          <el-table-column align="center" show-overflow-tooltip label="文件名">
            <template #default="{ row }">{{ row.name }}</template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="175" fixed="right">
            <template #default="{ row }">
              <el-button type="text" v-if="checkTypes.handler===1" @click="handleDeleteUpload(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item
          v-if="canUploadFile"
          label="该项目无需提交审批材料"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checksVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveChecks">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  doDelete,
  doFiled,
  getCheckTypes,
  saveChecks,
} from '@/api/dc_projectList'
import {upload} from '@/api/common'
import Edit from './components/ProjectEdit'

export default {
  name: 'Activity',
  components: {Edit},
  data() {
    return {
      list: [],
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      queryForm: {
        page: 1,
        list_row: 10,
        keyword: '',
        activity_range: null,
        activity_start: '',
        activity_end: '',
      },
      canUploadFile: false,   //判断是否需要上传文件
      checksVisible: false,
      checkTypes: [],
      currentActivityId: null,
    }
  },
  watch: {
    'queryForm.activity_range'(range) {
      const [start, end] = range || ['', '']
      this.queryForm.activity_start = start
      this.queryForm.activity_end = end
    },
  },
  created() {
    this.fetchData()
  },
  methods: {
    setSelectRows(val) {
      this.selectRows = val
    },
    handleEdit(row) {
      if (row.id) {
        this.$refs['edit'].showEdit(row)
      } else {
        this.$refs['edit'].showEdit()
      }
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const msg = await doDelete({activity_id: row.id})
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join()
          this.$baseConfirm('你确定要删除选中项吗', null, async () => {
            const {msg} = await doDelete({ids})
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          this.$baseMessage('未选中任何行', 'error')
          return false
        }
      }
    },
    handleDeleteUpload(row) {
      console.log(2222222, row)
      console.log(2222223, this.checkTypes)
      let resdata = this.checkTypes.fileList;
      let index = 0;
      for (let i = 0; i < resdata.length; i++) {
        if (resdata[i].uid === row.uid) {
          index = i;
        }
      }
      this.checkTypes.fileList.splice(index, 1)
      console.log(2222224, this.checkTypes)

      /*if (row.name) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const msg = await doDelete({activity_id: row.name})
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join()
          this.$baseConfirm('你确定要删除选中项吗', null, async () => {
            const {msg} = await doDelete({ids})
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          this.$baseMessage('未选中任何行', 'error')
          return false
        }
      }*/
    },
    handleFiled(row) {
      const actionText = row.is_filed === '是' ? '解档' : '归档'
      const isFiledNew = row.is_filed === '是' ? '否' : '是'
      this.$baseConfirm(`你确定要${actionText}当前项吗`, null, async () => {
        const msg = await doFiled({
          activity_id: row.id,
          is_filed: isFiledNew,
        })
        this.$baseMessage(msg, 'success')
        this.fetchData()
      })
    },
    handleExpenses(row) {
      const {id: activity_id, activity_title} = row
      this.$router.push({
        name: 'ProjectExpenses',
        query: {activity_id, activity_title},
      })
    },
    handleSizeChange(val) {
      this.queryForm.list_row = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.page = 1
      this.fetchData()
    },
    async fetchData() {
      this.listLoading = true
      const {data, total} = await getList(this.queryForm)
      this.list = data
      this.total = total
      this.listLoading = false
    },
    showChecks(id) {
      this.currentActivityId = id
      getCheckTypes({activity_id: id}).then((res) => {
        console.log(res)
        this.canUploadFile = !res.length
        let types = {
          fileList: []
        }
        if (res[0]) {
          types = {
            ...res[0],
            fileList: res[0].check_img.map((img) => ({
              uid: Math.random(),
              name: img.split('/').pop(),
              url: img,
            })),
          }
        }
        // types.unshift({ id: 0, project_category: '未分配', fileList: [] })
        this.checkTypes = types
        console.log(2233, this.checkTypes)
        this.checksVisible = true
      })
    },
    handleSaveChecks() {
      if (!this.validateChecks()) return
      const images = []
      const types = this.checkTypes
      const files = types.fileList
      const typeImages = files.map((file) => file.url).join()
      images.push({
        activity_expenses_id: types.id,
        check_img: typeImages,
      })
      const imagesJson = JSON.stringify(images)
      saveChecks({
        activity_id: this.currentActivityId,
        check_img: imagesJson,
      }).then((res) => {
        this.checksVisible = false
        this.$baseMessage(res, 'success')
      })
    },
    onChecksExceed() {
      this.$baseMessage('最多只能上传 6 张图片哦', 'warning')
    },
    onChecksChange(fileList) {
      console.log(223344, fileList)
      // 注: fileList 包含全部图片
      // 处理待上传图片
      const formData = new FormData()
      /* fileList
         .filter((file) => file.raw)
         .forEach((file) => formData.append('file[]', file.raw))

       const urls = res.url
       this.checkTypes.fileList = [
         ...fileList.filter((file) => !file.raw),
         ...urls.map((url) => ({url, name: url.split('/').pop()})),
       ]*/
      formData.append('file[]', fileList.raw)
      // 上传图片
      console.log(2233445, formData, fileList)
      upload(formData).then((res) => {
        // 上传后处理
        console.log(22334455, res)
        console.log(223344556, this.checkTypes)
        let fileLists = {
          name: '',
          url: ''
        }
        fileLists.name = res.url[0].split('/').pop();
        fileLists.url = res.url[0];
        console.log(123, fileLists)
        this.checkTypes.fileList.push(fileLists)
        console.log(2233445566, this.checkTypes.fileList)
      })

    },
    getUploadTypeLabel(type, index) {
      let label = type.project_category
      const num = type.fileList.length
      // label += ` ${index ? `(${num}/6)` : num}`
      label += ` (${num}/6)`
      return label
    },
    validateChecks() {
      const types = this.checkTypes
      const files = types.fileList
      // if (files.length < 1) {
      //   this.$baseMessage(
      //     `请上传至少 1 张图片至${types.project_category}`,
      //     'error',
      //   )
      //   return false
      // }
      for (const file of files) {
        if (file.url.startsWith('blob:')) {
          this.$baseMessage('图片上传中，请重试', 'error')
          return false
        }
      }
      return true
    },
    removeCheck(typeIndex, fileIndex) {
      this.checkTypes.fileList.splice(fileIndex, 1)
      this.$forceUpdate()
    },
  },
}
</script>

<style lang="scss" scoped>
.search-input {
  width: 250px;
}

.checks-row {
  display: flex;
  align-items: center;
}

.check-item {
  position: relative;
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  margin-right: 10px;
  background-position: center;
  background-size: cover;
  border: 1px solid #c0ccda;
  border-radius: 7px;
}

.check-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: 0.3s;
}

.check-item:hover .check-mask {
  opacity: 1;
}

.check-delete {
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
  transform: translate(-50%, -50%);
}

::v-deep .el-upload--picture-card {
  position: relative;
  width: 100px;
  height: 100px;
}

.check-add {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
